package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exceptions.LeadnewsException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JsonUtils;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Autowired //密码加密
    private BCryptPasswordEncoder encoder;

    @Override
    public Map<String, String> login(AdUserLoginDto dto) {
        //判断用户名密码是否为空
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            throw new LeadnewsException(AppHttpCodeEnum.PARAM_INVALID);//返回自定义异常:无效参数
        }
        //使用用户名查询用户
        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AdUser::getName, dto.getName());
        AdUser adUser = getOne(queryWrapper);
        if (adUser == null){
            throw new LeadnewsException(AppHttpCodeEnum.ADUSER_PASSWORD_ERROR);
        }
        //数据库加密后的密码
        String encodePwd = adUser.getPassword();
        //验证密码
        boolean b = encoder.matches(dto.getPassword(), encodePwd);
        if (!b){
            throw new LeadnewsException(AppHttpCodeEnum.ADUSER_PASSWORD_ERROR);
        }
        //生成token
        String token = JwtUtils.generateTokenExpireInSeconds(adUser.getId(), 3600);
        //构造返回对象
        AdUserDto adUserDto = BeanHelper.copyProperties(adUser, AdUserDto.class);
        Map<String, String> map = new HashMap<>();
        map.put("user", JsonUtils.toString(adUserDto));
        map.put("token",token);
        return map;
    }
}
